<?php
session_start();
require_once('../inc/db_access.inc');
require_once('../inc/utils.inc');
require_once('../inc/notes.inc');
require_once('../inc/wall.inc');
$uid =  $_SESSION['uid'];

if(!isset($uid)){
	die("user not logged in");
}
$dbc = new DBConnection();
$dbc->getNewConnection();

$operation = $_REQUEST['operation'];
$response = array();
if($operation == 'add_note'){
	$noteres = array();
	$note = $_REQUEST['note_txt'];

	if($note){
        	$note_id = add_note($dbc, $uid, $note);
		$noteres['note_id'] = $note_id;
		$noteres['note_txt'] = $note;
	        $tags = $_REQUEST['note_tags'];
        	if($tags){
                	add_tags($dbc, $uid, $note_id, $tags);
			$noteres['note_tags'] = $tags;
	        }
	$response['notes'] = array();
	$response['notes'][] = $noteres;
	}
} else if($operation == 'get_all_notes'){
	$notes = get_notes($dbc, $uid);
	$response['notes'] = array();
	foreach ($notes as $note){
		$noteres = array();
		$nid = $note['note_id'];
		$tags = get_tags($dbc, $uid, $nid);
		$taglist = '';
		foreach( $tags as $tag){
                	if($taglist != '')
                        	$taglist .= ', ';
                        $taglist .= $tag;
               	}
		$noteres['note_id'] = $nid;
		$noteres['note_txt'] = $note['note_txt'];
		$noteres['note_tags'] = $taglist;
		$response['notes'][] = $noteres;
	}
} else if($operation == 'get_wall_notes'){
	$wid = $_REQUEST['wall_id'];
	if($wid){
		$wn = get_wall_notes($dbc, $uid, $wid);
		$wnres = array();
		$wnres['wall_id'] = $wid;
		$wnres['notes'] = $wn;
		$response['wall_notes'] = $wnres;
	
	}
} else if($operation == 'add_notepad'){
	$wall_id = $_REQUEST['wall_id'];
	$taglist = $_REQUEST['taglist'];

	if($wall_id && $taglist){
		$np = add_wall_notes($dbc, $uid, $wall_id, $taglist);
		$wnres = array();
		$wnres['wall_id'] = $wall_id;
		$wnres['notes'] = $np;
		$response['wall_notes'] = $wnres;
		
	}
} else if($operation == 'get_sp_notes'){
	$taglist = $_REQUEST['taglist'];
	$tags = str_to_array($taglist);
	$notes = get_tag_notes($dbc, $uid, $tags);
	$response['scratchpad'] = $notes;
	
}
$response['status'] = 'success';

echo json_encode($response) . "\n";
?>
